<template>
  <div class="products-list-wrap">
    <el-container>
      <el-aside width="200px">
        <el-tree
          :default-expand-all="false"
          :data="treeData"
          :props="{
            children: 'children',
            label: 'preview'
          }"
          highlight-current
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node text-over">
              <span class="text-over" :title="node.label">{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </el-aside>
      <el-main>
        <div class="left" style="height: 100%">
          <div
            div
            class="right-list-wrap"
            v-infinite-scroll="load"
            infinite-scroll-distance="5"
            :infinite-scroll-immediate="false"
          >
            <div class="action-wrap">
              <el-form :model="form" ref="formRef" :inline="true" label-width="auto" style="max-width: 600px">
                <el-form-item
                  prop="partNum"
                  :label="optionInfo.productType === 1 ? '主材数量:' : '辅材数量:'"
                  :rules="{ required: false, message: '请输入', trigger: ['blur'] }"
                >
                  <!-- <el-input v-model="form.partNum" oninput="value=value.replace(/[^0-9]/g, '')" style="width: 100px" /> -->
                  <p>{{ _detail?.limitProductNum }}</p>
                </el-form-item>
                <el-form-item prop="money" label="限制金额:" :rules="{ required: false, message: '请输入', trigger: ['blur'] }">
                  <!-- <el-input
                    v-model="form.money"
                    oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                    style="width: 100px"
                  /> -->
                  <p>¥{{ _detail?.limitProductMoney || "-" }}</p>
                </el-form-item>
              </el-form>
              <div style="flex: 1; text-align: right">
                <el-button type="primary" link @click="isOpen = true">更多筛选</el-button>
              </div>
            </div>

            <div class="list-wrap">
              <template v-if="list.length > 0">
                <div class="list-item" v-for="item in list" :key="item.id">
                  <div>
                    <div class="prod-info">
                      <div class="top">
                        <div class="img"><img :src="item.mainPicUrl" alt="" /></div>
                        <div class="info">
                          <h3 class="name text-over" style="max-width: 300px">{{ item.productName || "-" }}</h3>
                          <p style="white-space: break-spaces; word-break: break-all">上架类目：{{ item.preview || "-" }}</p>
                          <p>型号：{{ item.modeCode || "-" }}</p>
                          <p>ID：{{ item.productId || "-" }}</p>
                        </div>
                      </div>
                      <footer>
                        <div>
                          <p>
                            <!-- 价格：<span style="color: #ff3333">¥{{ item.businessLowestPrice || "-" }}</span> -->
                          </p>
                          <el-button type="primary" size="small" @click="openSku(item)">添加</el-button>
                        </div>
                        <!-- <div class="tips">备注：{{ item.remark || "-" }}</div> -->
                      </footer>
                      <!-- 右上仓库角标 -->
                      <!-- <div class="warehouse-icon">xx</div> -->
                    </div>
                  </div>
                </div>
              </template>
              <div v-else style="display: flex; justify-content: center; width: 100%">
                <el-empty description="暂无数据" />
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 更多品牌筛选 -->
    <brandFilter ref="brandFilterRef" v-model:isOpen="isOpen" :filterData="filterData" @changeAttr="changeAttr" />

    <!-- 商品详情-选具体的sku -->
    <prodDetail :optionInfo="optionInfoDetail" @close="close" />
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
const route = useRoute();
import { Search } from "@element-plus/icons-vue";
import prodDetail from "./prodDetail.vue";
import brandFilter from "./brandFilter.vue";
import {
  categoryList,
  getPage,
  getPageV2,
  getProductDetail,
  getTempProductList,
  queryStastsList,
  queryCache,
  conditionInsideQuery,
  categoryListV2
} from "@/apis/quote-price/following";

const form = ref({});
const formRef = ref();
const brandFilterRef = ref();
const treeData = ref([]);
const list = ref([]);
const optionInfoDetail = ref({
  isShow: false,
  detail: {}
});
const isOpen = ref(false); //是否打开更多筛选抽屉
const filterData = ref([]);
const selected = ref([]); //选中的sku
const pagination = ref({
  page: 1,
  size: 50,
  total: 0
});

const emit = defineEmits(["update:isOpen", "close", "changeCate"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isMounted: false, //是否需要执行onMounted
        isShow: false,
        activeName: null, //1-条件内 2-条件外
        budgetId: "",
        contentId: "",
        productType: -1, //1-主材 2-辅材
        detail: {}, //组合添加的cailiaoDetailList组件的列表数据
        project: {} //项目obj
      };
    }
  }
});

const _detail = ref(props.optionInfo.detail);

watch(
  () => props.optionInfo.detail,
  val => {
    if (val) {
      console.log("bbbbbbbbbb传递过来得值===", val);
      _detail.value = val;
      if (props.optionInfo.isMounted) {
        // console.log("是否需要执行onMounted", props.optionInfo.isMounted);
        categoryListFun();
      }
    }
  },
  { deep: true }
);

const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

onMounted(async () => {
  // categoryListFun();
});

//筛选品牌-列表查询
const queryStastsListFun = () => {
  queryStastsList({
    categoryId: currCate.value.categoryId,
    productType: props.optionInfo.productType === 1 ? null : props.optionInfo.productType === 2 ? 2 : 0 //  2-查询辅材  null-查询主材 0-查询全部
  }).then(res => {
    if (res.code === 200) {
      filterData.value = res.data;
    }
  });
};

//属性筛选id改变时的回调
const _filterVal = ref([]);
const _filterVal3 = ref([]);
const _brandIds = ref([]);
const changeAttr = ({ filterVal, filterVal3, brandIds }) => {
  console.log("子组件返回的数据===", filterVal, filterVal3, brandIds);
  _filterVal.value = filterVal;
  _filterVal3.value = filterVal3;
  _brandIds.value = brandIds;

  const attrIds2 = _filterVal.value.flat(); //选中的二级属性ids
  for (let ids2 of attrIds2) {
    const str = _filterVal3.value.find(item => typeof item === "string" && item.includes(ids2));
    !str && _filterVal3.value.push(ids2);
  }
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getList(); //属性筛选接口请求
};

//查询分类tree
const categoryListFun = async () => {
  await categoryListV2({
    productType: props.optionInfo.productType,
    budgetId: props.optionInfo.budgetId,
    contentId: props.optionInfo.contentId
  }).then(res => {
    if (res.code === 200) {
      treeData.value = res.data;
    }
  });
};

const openSku = item => {
  getProductDetail({ productId: item.productId }).then(res => {
    if (res.code === 200) {
      optionInfoDetail.value.isShow = true;
      optionInfoDetail.value.detail = res.data;
      optionInfoDetail.value.prodObj = item;
      optionInfoDetail.value.activeName = props.optionInfo.activeName;
    }
  });
};
const close = () => {
  optionInfoDetail.value.isShow = false;
  console.log("查询暂存的商品sku", JSON.parse(localStorage.getItem("followingObj"))._time);
  getTempProductListFun();
};
//查询暂存的商品sku
const getTempProductListFun = () => {
  if (props.optionInfo.activeName) {
    queryCache({ code: JSON.parse(localStorage.getItem("followingObj"))._time }).then(res => {
      if (res.code === 200) {
        selected.value = res.data || [];
        emit("changeCate", { total: pagination.value.total, selected: selected.value });
      }
    });
  } else {
    getTempProductList({ code: JSON.parse(localStorage.getItem("followingObj"))._time }).then(res => {
      if (res.code === 200) {
        selected.value = res.data || [];
        emit("changeCate", { total: pagination.value.total, selected: selected.value });
      }
    });
  }
};

//分类更改
const currCate = ref({}); //当前选中的分类
const oldNode = ref({ categoryId: null });
const handleNodeClick = async val => {
  // console.log("当前分类===", val);
  if (val.children.length > 0) return;
  if (oldNode.value.categoryId !== val.categoryId) {
    reset(false);
    currCate.value = val;
    resetPagination(); //清空页面上的list数据，重置page=1 size=50
    getList();
  }
  oldNode.value = val;
};

//清空商品列表，并且清空选中的tree节点
const resetPageList = () => {
  currCate.value = {};
  list.value = [];
};

const load = () => {
  console.log("触底了，要请求分页查询接口 getList();");
  if (list.value.length < pagination.value.total) {
    pagination.value.page++;
    getList();
  }
};

const resetPagination = () => {
  list.value = [];
  pagination.value.page = 1;
  pagination.value.size = 50;
};

const refresh = () => {
  resetPagination(); //清空页面上的list数据，重置page=1 size=50
  getList();
};

//分类查询商品列表  isClear-在查询之前，是否清空list数据
const getList = async (isClear = false) => {
  if (currCate.value.categoryId) {
    //分类查询属性11111111111
    if (isClear) list.value = [];

    //查询商品列表222222222222
    getPageV2({
      brandIds: _brandIds.value, //品牌id
      productType: props.optionInfo.productType === 1 ? null : props.optionInfo.productType === 2 ? 2 : 0, //  2-查询辅材  null-查询主材 0-查询全部
      budgetId: props.optionInfo.budgetId,
      contentId: props.optionInfo.contentId,
      quotaId: props.optionInfo.project.quotaId,
      categoryId: currCate.value.categoryId,
      page: pagination.value.page,
      size: pagination.value.size
    }).then(res2 => {
      if (res2.code === 200) {
        list.value = [...list.value, ...res2.data.list];
        pagination.value.total = res2.data.total;

        queryStastsListFun(); //查询品牌筛选数据
        emit("changeCate", { total: pagination.value.total, selected: selected.value });
      }
    });
  }
};

/**
 *
 * @param isClearSelected  是否需要清空选中的sku
 */
const reset = (isClearSelected = true) => {
  if (isClearSelected) selected.value = [];

  form.value = {};
  formRef.value.resetFields();
  if (isClearSelected) selected.value = [];

  _filterVal.value = [];
  _filterVal3.value = [];
  _brandIds.value = [];

  //清空组件筛选
  brandFilterRef.value.reset();
};

const clickClose = () => {
  _isOpen.value = false;
  // emit("close");
};

defineExpose({ reset, getList, refresh, getTempProductListFun, resetPageList, categoryListFun });
</script>

<style lang="scss">
.sku-selected-drawer.el-overlay {
  .el-drawer {
    width: 1160px !important;
    box-shadow: -8px 0px 16px 0px rgba(0, 38, 73, 0.1);
    border-radius: 10px 0px 0px 10px;
  }
  .el-drawer__header {
    border: 1px solid #dcdfe6;
    margin-bottom: 0;
    padding-bottom: 24px;
    color: #131414;
    font-size: 18px;
  }
  .el-drawer__footer {
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 14px 20px;
  }
  .col1 {
    & > div {
      display: flex;
    }

    .left {
      img {
        width: 80px;
        height: 80px;
        border-radius: 4px;
      }
    }
    .right {
      padding-left: 18px;
      .name {
        font-size: 14px;
        color: #3d3d3d;
        margin-bottom: 5px;
      }
      p {
        font-size: 12px;
        color: #86909c;
        margin-bottom: 5px;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
:deep(.el-tree) {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 94px;

  .el-icon.el-tree-node__expand-icon {
    padding-left: 10px;
  }

  .el-tree-node__content {
    line-height: 32px;
    height: 32px;
  }
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #eef1f4 !important;
    color: #1a1a1a;

    .custom-tree-node i {
      color: #1a1a1a !important;
    }
  }
}

.el-button--primary {
  --el-button-bg-color: #424e66;
  border: none;
}
.el-button.el-button--info {
  --el-color-info: #f2f3f5;
  --el-color-white: #1d2129;
  &:hover {
    --el-button-hover-bg-color: #f2f3f5 !important;
    border-color: #f2f3f5 !important;
  }
}
.products-list-wrap {
  height: 600px;
  overflow: auto;
  :deep(.el-container) {
    height: 100%;
  }
  :deep(.el-aside) {
    padding-top: 10px;
  }
  :deep(.el-main) {
    border-left: 1px solid #e2e8f0;
    padding: 0 20px;
    & > .left {
      .action-wrap {
        position: sticky;
        top: 0;
        z-index: 2;
        background-color: white;
        height: 72px;
        display: flex;
        align-items: center;
        .el-form-item {
          margin-bottom: 0;
        }
      }
      .list-wrap {
        display: flex;
        flex-wrap: wrap;
      }
    }
  }
}
</style>
